import logst.parsers_base as parsers_base
import time

class restarts_Parser(parsers_base.base_Parser_class):

   def initialize(self):

      self.add_option("kerver", "Detect kernel version changes")

   def init_activators(self):

      self.add_regex_activator('syslogd .*: restart.$', self.parse_line)

      if self.get_option("kerver").is_true():
         self.add_regex_activator('Linux version', self.kernel_version_change)

   def kernel_version_change(self, log):

      newker = log.message()[14:]

      tline = self.get_variable(host = log.hostname(), name = "kernel_timeline")

      if not tline:

         tline = []

      elif tline[-1][1] != newker:

         log.add_event( 'Kernel version changed', long_text = '<table><tr><td>Previous:<td>%s<tr><td>Current:<td>%s</table>' % (tline[-1][1], newker) )

      tline.append( (log.date(), newker) )

      self.set_variable(host = log.hostname(), name = "kernel_timeline", value = tline)

   def parse_line(self, log):

      other_log = log.next()

      if other_log and other_log.message().startswith("klogd "):
         self.add_event(log, text = "System restarted", icon = "images/32px-Crystal_Clear_app_display.png")
         return

      other_log = log.previous()

      if not other_log:
         self.add_event(log, text = "Syslog restart (system possibly restarted)", icon = "images/32px-Crystal_Clear_app_display.png")

      elif time.mktime(log.time()) - time.mktime(other_log.time()) > 30:
         self.add_event(log, text = "System restarted", icon = "images/32px-Crystal_Clear_app_display.png")

      # else it was a normal restart of syslogd.

      return
